package com.android.thought.badboys;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import android.app.ProgressDialog;
import android.content.Context;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.android.thought.badboys.Action.IBackupAccessAction;
import com.android.thought.badboys.Info.ListBackup;

public class BackupFileSaveTask extends AsyncTask<ListBackup, ProgressDialog, Boolean> {

	Context mContext;
	ProgressDialog mDlg;
	int mSeqNumber = 0;

	MediaScannerConnection mConnection;
	IBackupAccessAction mListener;
	
	public BackupFileSaveTask(Context context, IBackupAccessAction listener ) {
		mContext = context;

		mListener = listener;
		mDlg = new ProgressDialog(mContext);
		mDlg.setIndeterminate(true);
		mDlg.setCancelable(true);
		mDlg.setMessage("잠시만 기다려 주세요. ");
		mDlg.show();
	}

	@Override
	protected Boolean doInBackground(ListBackup... params) {

		ObjectOutputStream outStream = null;
		final String fileName = mContext.getApplicationInfo().dataDir + "/listBackup.txt";

		
		try {
			ListBackup info = params[0];

			File file = new File(fileName);

			if (!file.exists())
				file.createNewFile();

			outStream = new ObjectOutputStream(new FileOutputStream(file));

			outStream.writeObject(info);
			outStream.flush();
			

		} catch (Exception e) {
			
			Log.e("CH_DEBUG", "######### 왜 실패냐  : " + e.toString());
			return false;
		} finally {
			try {
				if (outStream!= null) {
					outStream.close();
				}

				scanImage(fileName);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return true;
	}

	@Override
	protected void onPostExecute(Boolean result) {
		super.onPostExecute(result);
		
		if ( mListener != null ) 
			mListener.onSaveComplated(result);

		mDlg.dismiss();

		Toast.makeText(mContext, result ? "파일 저장 완료 하였습니다." : "파일 저장을 실패 하였습니다.", Toast.LENGTH_SHORT).show();

	}

	private void scanImage(final String imageFileName) {
		mConnection = new MediaScannerConnection(mContext, new MediaScannerConnectionClient() {
			@Override
			public void onMediaScannerConnected() {
				mConnection.scanFile(imageFileName, null);
			}

			@Override
			public void onScanCompleted(String path, Uri uri) {
				mConnection.disconnect();
				mConnection = null;
			}
		});
		mConnection.connect();
	}

}
